<template>
  <div>
    <div class="container">
      <div class="button">
        <el-button type="primary"
                   size="mini"
                   @click="openDialog()">添加自选</el-button>
        <!-- 通过 :show-dialog 绑定子组件的 showDialog 属性 -->
        <StockDialog :showDialog="showDialog"
                     @close-dialog="closeDialog" />
      </div>

      <el-form :model="queryParams"
               ref="queryForm"
               size="small"
               :inline="true"
               label-width="80px">
        <el-form-item label="股票名称"
                      prop="stockName">
          <el-input v-model="queryParams.stockName"
                    placeholder="请输入股票名称"
                    clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary"
                     icon="el-icon-search"
                     size="mini"
                     @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
                     size="mini"
                     @click="resetQuery">重置</el-button>
          <el-button type="primary"
                     icon="el-icon-refresh"
                     size="mini"
                     @click="handleUpdate">更新</el-button>
        </el-form-item>

      </el-form>
    </div>
    <el-table :data="tableData"
              style="width: 100%"
              :row-class-name="tableRowClassName"
              @sort-change="sortChange">
      <!-- <el-table-column type="index"
                       label="id"
                       fixed
                       width="50">
      </el-table-column> -->
      <el-table-column prop="stockSymbol"
                       label="股票代码"
                       fixed
                       width="120">
        <template slot-scope="scope">
          <el-popover @show="handleClick(scope.row, scope.$index)"
                      trigger="click"
                      placement="right">
            <v-chart :option="option"
                     autoresize
                     style="width: 800px; height: 500px;"></v-chart>

            <!-- <p>代码: {{ scope.row.stockSymbol }}</p>
            <p>名称: {{ scope.row.stockName }}</p> -->

            <div slot="reference"
                 class="name-wrapper">
              <el-tag size="medium">{{ scope.row.stockSymbol }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="stockName"
                       label="股票名称"
                       sortable="custom"
                       fixed
                       width="120">
      </el-table-column>

      <el-table-column prop="consecutiveDaysLimitUp"
                       sortable="custom"
                       label="连板天数">
      </el-table-column>
      <el-table-column prop="daysLimitUp"
                       sortable="custom"
                       label="涨停天数">
      </el-table-column>
      <el-table-column prop="highestPrice"
                       label="最高价">
      </el-table-column>
      <el-table-column prop="highestDate"
                       width="140"
                       :formatter="formatDate"
                       label="最高价日期">
      </el-table-column>
      <el-table-column prop="lowestPrice"
                       label="最低价">
      </el-table-column>
      <el-table-column prop="lowestDate"
                       width="140"
                       :formatter="formatDate"
                       label="最低价日期">
      </el-table-column>
      <el-table-column prop="volatility"
                       label="波动率">
      </el-table-column>
      <el-table-column prop="highestPrice"
                       :formatter="formatNumber"
                       label="65反弹">
      </el-table-column>
      <el-table-column prop="highestPrice"
                       :formatter="formatNumber1"
                       label="70反弹">
      </el-table-column>
      <el-table-column label="Cal Column"
                       width="160">
        <!-- 新增的输入列 -->
        <template slot-scope="scope">
          <el-input v-model.number="scope.row.inputColumn"
                    type="number"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="结果列">
        <template slot-scope="scope">
          <!-- 计算每行独立的B列 -->
          {{ (scope.row.highestPrice * scope.row.inputColumn).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="currentPrice"
                       fixed="right"
                       label="现价">
      </el-table-column>
      <el-table-column label="现价波动率"
                       fixed="right">
        <template slot-scope="scope">
          <!-- 计算每行独立的B列 -->
          {{ (scope.row.currentPrice / scope.row.highestPrice).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="danger"
                     @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">

      <el-pagination background
                     style="margin-top: 20px;"
                     layout="total, sizes, prev, pager, next"
                     :total="pagination.total"
                     :current-page.sync="queryParams.pageNum"
                     :page-size="queryParams.pageSize"
                     :page-sizes="[10, 20, 50, 100]"
                     @current-change="getList"
                     @size-change="handleSizeChange">
      </el-pagination>
    </div>
  </div>

</template>

<script>
import StockDialog from './StockDialog.vue';
import ECharts from 'vue-echarts'

const upColor = '#ec0000';
const downColor = '#00da3c';

var option = {
  title: {
    text: '',
    left: 0
  },
  animation: false,
  legend: {
    bottom: 10,
    left: 'center',
    data: ['日k', 'MA5', 'MA10', 'MA20']
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    textStyle: {
      color: '#000'
    },
    position: function (pos, params, el, elRect, size) {
      const obj = {
        top: 10
      };
      obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
      return obj;
    }
    // extraCssText: 'width: 170px'
  },
  axisPointer: {
    link: [
      {
        xAxisIndex: 'all'
      }
    ],
    label: {
      backgroundColor: '#777'
    }
  },
  toolbox: {
    feature: {
      dataZoom: {
        yAxisIndex: false
      },
      brush: {
        type: ['lineX', 'clear']
      }
    }
  },
  brush: {
    xAxisIndex: 'all',
    brushLink: 'all',
    outOfBrush: {
      colorAlpha: 0.1
    }
  },
  visualMap: {
    show: false,
    seriesIndex: 5,
    dimension: 2,
    pieces: [
      {
        value: 1,
        color: upColor
      },
      {
        value: -1,
        color: downColor
      }
    ]
  },
  grid: [
    {
      left: '10%',
      right: '8%',
      height: '50%'
    },
    {
      left: '10%',
      right: '8%',
      top: '63%',
      height: '16%'
    }
  ],
  xAxis: [
    {
      type: 'category',
      data: [],
      boundaryGap: false,
      axisLine: { onZero: false },
      splitLine: { show: false },
      min: 'dataMin',
      max: 'dataMax',
      axisPointer: {
        z: 100
      }
    },
    {
      type: 'category',
      gridIndex: 1,
      data: [],
      boundaryGap: false,
      axisLine: { onZero: false },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: { show: false },
      min: 'dataMin',
      max: 'dataMax'
    }
  ],
  yAxis: [
    {
      scale: true,
      splitArea: {
        show: true
      }
    },
    {
      scale: true,
      gridIndex: 1,
      splitNumber: 2,
      axisLabel: { show: false },
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false }
    }
  ],
  dataZoom: [
    {
      type: 'inside',
      xAxisIndex: [0, 1],
      start: 50,
      end: 100
    },
    {
      show: true,
      xAxisIndex: [0, 1],
      type: 'slider',
      top: '85%',
      start: 50,
      end: 100
    }
  ],
  series: [
    {
      name: '日k',
      type: 'candlestick',
      data: [],
      itemStyle: {
        color: upColor,
        color0: downColor,
        borderColor: undefined,
        borderColor0: undefined,
      },
      markPoint: {
        label: {
          normal: {
            formatter: function (param) {
              return param != null ? Math.round(param.value) : '';
            }
          }
        },
        data: [{
          name: 'XX标点',
          coord: ['2022/12/12', 2300],
          value: 2300,
          itemStyle: {
            normal: {
              color: 'rgb(41,60,85)'
            }
          }
        }, {
          name: 'highest value',
          type: 'max',
          valueDim: 'highest'
        }, {
          name: 'lowest value',
          type: 'min',
          valueDim: 'lowest'
        }, {
          name: 'average value on close',
          type: 'average',
          valueDim: 'close'
        }],
        tooltip: {
          formatter: function (param) {
            return param.name + '<br>' + (param.data.coord || '');
          }
        }
      },
      markLine: {
        symbol: ['none', 'none'],
        data: [
          [{
            name: 'from lowest to highest',
            type: 'min',
            valueDim: 'lowest',
            symbol: 'circle',
            symbolSize: 10,
            label: {
              normal: {
                show: false
              },
              emphasis: {
                show: false
              }
            }
          }, {
            type: 'max',
            valueDim: 'highest',
            symbol: 'circle',
            symbolSize: 10,
            label: {
              normal: {
                show: false
              },
              emphasis: {
                show: false
              }
            }
          }], {
            name: 'min line on close',
            type: 'min',
            valueDim: 'close'
          }, {
            name: 'max line on close',
            type: 'max',
            valueDim: 'close'
          }
        ]
      }
    },
    {
      name: 'MA5',
      type: 'line',
      data: [],
      smooth: true,
      lineStyle: {
        opacity: 0.5
      }
    },
    {
      name: 'MA10',
      type: 'line',
      data: [],
      smooth: true,
      lineStyle: {
        opacity: 0.5
      }
    },
    {
      name: 'MA20',
      type: 'line',
      data: [],
      smooth: true,
      lineStyle: {
        opacity: 0.5
      }
    },
    {
      name: 'Volume',
      type: 'bar',
      xAxisIndex: 1,
      yAxisIndex: 1,
      data: [],
      itemStyle: {
        normal: {
          color: function (params) {
            var colorList;
            if (params.data[2] == 1) {
              colorList = downColor;
            } else {
              colorList = upColor;
            }
            return colorList;
          },
        },
      },
    }
  ]
}

export default {
  components: {
    StockDialog,
    'v-chart': ECharts,
  },
  data () {
    return {
      showDialog: false,
      tableData: [],
      stockSymbol: 'sh600519',
      stockSymbols: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: '',
        isAsc: '',
        stockName: '',
      },
      pagination: {
        total: 0,
      },
      socket: null,
      latestData: '',
      xData: [],
      yData: [],
      option: option
    }
  },

  methods: {
    tableRowClassName ({ row }) {
      if (row.volatility <= 0.65) {
        return 'success-row';
      } else if (row.volatility <= 0.70) {
        return 'warning-row';
      }
      return '';
    },
    formatDate (row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    formatNumber (row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      let dt = data * 0.65;
      return dt.toFixed(2);
    },
    formatNumber1 (row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      let dt = data * 0.7;
      return dt.toFixed(2);
    },
    getList () {
      this.$http.get('/stock/index', this.queryParams).then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data.records;
          this.pagination.total = res.data.data.total;
          this.getStockCurrentPrice();
          console.log(res.data.data.records);
        }
      });
    },
    handleSizeChange (val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    handleUpdate () {
      this.$http.get('/stock/update').then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: '更新成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: '更新失败',
            type: 'error'
          });
        }
        this.getList();
      });

    },
    handleClick (row) {
      this.stockSymbol = row.stockSymbol;
      this.getStockKLineList();
    },

    async getStockKLineList () {
      await this.$http.get('/stock/kline/' + this.stockSymbol).then(res => {
        if (res.data.code == 200) {
          this.stockLineData = res.data.data;
          this.updateEchartsData(this.stockLineData)
        }
      });
    },

    openDialog () {

      this.showDialog = true;
      console.log(this.showDialog)
    },
    closeDialog () {
      this.showDialog = false;
    },

    /*
    获取股票实时价格
    */
    getStockCurrentPrice () {
      this.stockSymbols = [];
      this.tableData.forEach(item => {
        this.stockSymbols.push(item.stockSymbol)
      });
      this.$http.post('/stock/current-price', this.stockSymbols).then(res => {
        if (res.data.code == 200) {
          let data = res.data.data;
          for (let i = 0; i < this.tableData.length; i++) {
            this.$set(this.tableData[i], "currentPrice", data[i].currentPrice);
          }
        }
      });
      console.log('获取当前价格 Method executed.');
    },
    startTimer () {
      // Set an interval to check the time and execute a function if it's within the specified range
      this.timer = setInterval(() => {
        const currentTime = new Date();
        const currentHours = currentTime.getHours();
        const currentMinutes = currentTime.getMinutes();


        // 定义时间范围（9:30 到 15:00）
        const startHours = 9;
        const startMinutes = 30;
        const endHours = 15;
        const endMinutes = 0;

        // 将当前时间转换为分钟数
        const currentTotalMinutes = currentHours * 60 + currentMinutes;
        const startTime = startHours * 60 + startMinutes;
        const endTime = endHours * 60 + endMinutes;


        // Check if the current time is between 9:30 AM and 3:00 PM
        if (currentTotalMinutes >= startTime && currentTotalMinutes <= endTime) {
          this.getStockCurrentPrice(); // Call your function here
        }
      }, 10000); // Check every minute (60,000 milliseconds)
    },
    stopTimer () {
      // Clear the interval when the component is about to be destroyed
      clearInterval(this.timer);
    },
    handleDelete (index, row) {

      let stock_symbol = row.stockSymbol;
      this.$http.delete('/stock/delete/' + stock_symbol).then(res => {
        if (res.data.code == 200) {
          console.log(res.data);
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
          this.closeDialog();
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
        this.getList();
      });
    },
    sortChange (column) {
      //打印可以分别得到上下箭头的数据
      console.log(column);
      if (column.order === 'descending') {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'desc'
      } else {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'asc'
      }
      this.queryParams.pageNum = 1;
      this.getList();//查询列表方法
    },
    /**
     * 更新echarts 图表数据
     * @param {} data 
     */
    updateEchartsData (data) {
      const stockKLineData = data.sinaStockList;
      const dateColumns = stockKLineData.map(row => [this.formatEchartDate(row.day)]);
      const dataColumns = stockKLineData.map(row => [row.open, row.close, row.low, row.high]);
      const m5data = stockKLineData.map(row => row.maPrice5);
      const m10data = stockKLineData.map(row => row.maPrice10);
      const m20data = stockKLineData.map(row => row.maPrice20);
      const volume = this.formatData(stockKLineData);
      option.title.text = data.stockName + "----" + data.stockSymbol;
      option.xAxis[0].data = dateColumns
      option.xAxis[1].data = dateColumns
      option.series[0].data = dataColumns
      option.series[1].data = m5data
      option.series[2].data = m10data
      option.series[3].data = m20data
      option.series[4].data = volume
      this.option = option
    },
    formatEchartDate (date) {
      let dt = new Date(date)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
    },
    formatData (rawData) {
      var volumes = [];
      for (var i = 0; i < rawData.length; i++) {
        console.log(rawData[i])
        volumes.push([i, rawData[i].volume, rawData[i].open > rawData[i].close ? 1 : -1]);
      }
      return volumes;
    },

  },


  created () {
    this.getList();
  },
  mounted () {
    this.startTimer();
  },
  beforeDestroy () {
    // Cleanup before the component is destroyed
    this.stopTimer();
  },

}
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
a {
  text-decoration: none;
}
.el-main {
  background-color: #ffffff;
  color: #333;
}
.container {
  display: flex;
}
.button {
  margin-right: 20px;
  margin-top: 3px;
}
</style>